package fr.afcepf.ai89.esharing.data;

import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import fr.afcepf.ai89.esharing.entity.MessagePrive;
import fr.afcepf.ai89.esharing.entity.Proprietaire;

@Stateless
public class DAOMessagePrive implements IDAOMessagePrive {

	@PersistenceContext(unitName = "ESharingPhase22")
	EntityManager em;

	@Override
	public MessagePrive getMsgPrive(int idMP) {
		
		Query hql = em.createQuery("SELECT mp FROM MessagePrive mp INNER JOIN FETCH mp.expediteur INNER JOIN FETCH mp.destinaire WHERE mp.idMsgPrive = :pmp");
		hql.setParameter("pmp", idMP);
		MessagePrive mp = (MessagePrive)hql.getSingleResult();
		
		return mp;
		
	}

	@Override
	public List<MessagePrive> getMsgsPrives() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<MessagePrive> getMsgsPrivesEnvoyes(Proprietaire exp) {

		Query hql = em.createQuery("SELECT mp FROM MessagePrive mp INNER JOIN FETCH mp.expediteur INNER JOIN FETCH mp.destinaire WHERE mp.expediteur.idUtilisateur = :pmp");
		hql.setParameter("pmp", exp.getIdUtilisateur());
		List<MessagePrive> mps = hql.getResultList();
		
		return mps;

	}

	@Override
	public int envoyerMsgPrive(MessagePrive msg) {
		
		msg.setDateEnvoiMsgPrive(new Date());
		em.persist(msg);
		
		Query hql = em.createQuery("SELECT MAX(idMsgPrive) FROM MessagePrive mp");
		int idMsg = (Integer)hql.getSingleResult();
		
		return idMsg;
		
	}

	@Override
	public int marquerLuMsgPrive(MessagePrive msg) {
		
		msg = (MessagePrive)em.find(MessagePrive.class, msg.getIdMsgPrive());
		msg.setDateReceptionMsgPrive(new Date());
		em.merge(msg);
		
		return msg.getIdMsgPrive();
		
	}

	@Override
	public List<MessagePrive> getMsgsPrivesRecus(Proprietaire des) {
		
		Query hql = em.createQuery("SELECT mp FROM MessagePrive mp INNER JOIN FETCH mp.expediteur INNER JOIN FETCH mp.destinaire WHERE mp.destinaire.idUtilisateur = :pmp");
		hql.setParameter("pmp", des.getIdUtilisateur());
		List<MessagePrive> mps = hql.getResultList();
		
		return mps;
		
	}

}
